<template>
  <div class="page-container">
    <!-- 头部导航 -->
    <header class="header">
        <div class="back-btn" @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          <span>返回</span>
        </div>
        <h1>编辑新闻</h1>
        <Time />
    
    </header>

    <div class="main-content">
      <div class="form-container">
        <div class="form-item">
          <label for="title">新闻题目</label>
          <el-input id="title" v-model="newsInfo.title" placeholder="请输入新闻题目"  />
        </div>
        <div class="form-item flex-container">
          <div class="left-column">
            <div class="form-item">
              <label for="summary">摘要</label>
              <el-input id="summary" v-model="newsInfo.summary" placeholder="请输入摘要" maxlength="36"  show-word-limit/>
            </div>
            <div class="form-item">
              <label for="author">作者</label>
              <el-input id="author" v-model="newsInfo.author" placeholder="请输入作者" />
            </div>
          </div>
          <div class="right-column">
            <div class="form-item">
              <label for="cover">封面图片</label>
              <el-upload 
                class="upload-button" 
                :action="`/api/admins/uploadCoverImg`"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :headers="uploadHeaders"
                name="file"
                accept="image/*"
                :loading="uploading"
              >
                <template v-if="newsInfo.coverImage">
                  <div class="image-container">
                    <img :src="newsInfo.coverImage" alt="封面图片" style="width: 100px; height: 100px; object-fit: cover;">
                    <div class="image-overlay">
                      <span>重新上传</span>
                    </div>
                    <div v-if="uploading" class="upload-loading">
                      <el-icon class="loading-icon"><Loading /></el-icon>
                      <span>上传中...</span>
                    </div>
                  </div>
                </template>
                <div v-else>
                  <el-button style="background-color: #bababa; height: 100px; width: 100px; color: black; border:none">
                    <template v-if="uploading">
                      <el-icon class="loading-icon"><Loading /></el-icon>
                      <span>上传中...</span>
                    </template>
                    <template v-else>
                      点击上传
                    </template>
                  </el-button>
                </div>
              </el-upload>
            </div>
          </div>
        </div>
        <div class="editor-container">
          <quill-editor 
            theme="snow" 
            contentType="html" 
            v-model:content="newsInfo.content"
            :options="editorOptions"
          ></quill-editor>
        </div>
        <el-button class="submit-button" type="primary" @click="handleSubmit" :loading="submitting">
          发布
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft ,Loading} from '@element-plus/icons-vue'
import { ElMessage ,ElMessageBox} from 'element-plus'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { addNews } from '@/api/news'
import { useTokenStore } from '@/stores/token.js'
import Time from '@/components/Time.vue'
import { useNewsStore } from '@/stores/news.js'
const tokenStore = useTokenStore()
const newsStore = useNewsStore()
const router = useRouter()

const submitting = ref(false)
const uploading = ref(false)


const newsInfo = ref({
  title: '',
  summary: '',
  author: '',
  coverImage: '',
  content: ''
})

// 编辑器配置
const editorOptions = {
  placeholder: '请输入新闻内容...',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'script': 'sub'}, { 'script': 'super' }],
      [{ 'indent': '-1'}, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['clean'],
      ['link', 'image']
    ]
  }
}

const uploadHeaders = computed(() => ({
  'Authorization': tokenStore.token,
  'Accept': 'application/json'
}))

// 上传前验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }

  uploading.value = true
  return true
}

// 上传成功回调
const handleUploadSuccess = (response) => {
  uploading.value = false
  if (response.code === 200 && response.data) {
    newsInfo.value.coverImage = response.data
    ElMessage.success('封面图片上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 上传失败回调
const handleUploadError = (error) => {
  uploading.value = false
  console.error('上传错误：', error)
  ElMessage.error('封面图片上传失败')
}

// 表单验证
const validateForm = () => {
  if (!newsInfo.value.title.trim()) {
    ElMessage.error('请输入新闻标题')
    return false
  }
  if (!newsInfo.value.summary.trim()) {
    ElMessage.error('请输入新闻摘要')
    return false
  }
  if (!newsInfo.value.author.trim()) {
    ElMessage.error('请输入作者')
    return false
  }
  if (!newsInfo.value.coverImage) {
    ElMessage.error('请上传封面图片')
    return false
  }
  if (!newsInfo.value.content.trim()) {
    ElMessage.error('请输入新闻内容')
    return false
  }
  return true
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) return

  try {
    submitting.value = true
    const response = await addNews(newsInfo.value)
    if (response.code === 200) {
      ElMessage.success('新闻发布成功')
      newsStore.fetchNewsData()
      router.push('/news')
    } else {
      ElMessage.error(response.msg || '发布失败')
    }
  } catch (error) {
    console.error('发布错误：', error)
    ElMessage.error('发布失败：' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

// 返回主页面
const handleBack = () => {
  ElMessageBox.confirm('确定要离开吗？未保存的内容将会丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    newsStore.fetchNewsData()
    router.back()
  }).catch(() => {})
}



</script>

<style scoped>
@import '@/assets/css/news/addNews.css';
@import '@/assets/css/header/index.css';
@import '@/assets/css/others/upload.css';

</style>
